package com.sfx.job;

import com.sfx.domain.entity.Article;
import com.sfx.service.ArticleService;
import com.sfx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sfx.constants.RedisConstants.ARTICLE_VIEWCOUNT_KEY;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-14
 * Time: 15:01
 */
@Component
public class ViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    /**
     * 更新浏览量到数据库中
     */
    @Scheduled(cron = "0/55 * * * * ?")
    public void updateViewCount(){
        //1.查询redis中的文章浏览量
        Map<String, Object> cacheMap = redisCache.getCacheMap(ARTICLE_VIEWCOUNT_KEY);
        //2.封装成Article的单列集合
        List<Article> articleList = cacheMap.entrySet().stream()
                .map(entry ->
                        new Article(Long.valueOf(entry.getKey()),
                                Long.valueOf(entry.getValue().toString())))
                .collect(Collectors.toList());
        //3.更新数据库
        articleService.updateBatchById(articleList);
    }
}